using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace OnlineAnadolu
{
    public partial class menemen2 : System.Web.UI.Page
    {
        int a = 0;
        HtmlTable tbl = new HtmlTable();

        string[] b = new string[100];
        Database db = new Database();
        void FillAuthors(MenuItem node)
        {
            string connString = System.Configuration.ConfigurationSettings.AppSettings["MyCon"];
            SqlConnection connection = new SqlConnection(connString);
            SqlCommand command = new SqlCommand("Select * From categories where parentid is null", connection);
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            DataSet authors = new DataSet();
            adapter.Fill(authors);
            if (authors.Tables.Count > 0)
            {
                foreach (DataRow row in authors.Tables[0].Rows)
                {
                    MenuItem newNode = new MenuItem();
                    newNode.Text = row["categoryname"].ToString();
                    newNode.Value = (row["categoryid"]).ToString();

                    // newNode.NavigateUrl = "../UrunGoster.aspx?CatID=" + (row["categoryid"]).ToString();

                    // newNode.SelectAction = TreeNodeSelectAction.Expand;
                    node.ChildItems.Add(newNode);

                    FillTitlesForAuthors(newNode);

                }
            }
        }

        void FillTitlesForAuthors(MenuItem node)
        {
            string authorID = node.Value.ToString();
            string connString = System.Configuration.ConfigurationSettings.AppSettings["MyCon"];
            SqlConnection connection = new SqlConnection(connString);
            SqlCommand command = new SqlCommand("Select categoryname, categoryid From categories Where parentid = '" + authorID + "'", connection);
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            DataSet titlesForAuthors = new DataSet();
            adapter.Fill(titlesForAuthors);
            if (titlesForAuthors.Tables.Count > 0)
            {
                foreach (DataRow row in titlesForAuthors.Tables[0].Rows)
                {
                    MenuItem newNode = new MenuItem();
                    newNode.Text = row["categoryname"].ToString();
                    newNode.Value = (row["categoryid"]).ToString();
                    //    newNode.NavigateUrl = "../UrunGoster.aspx?CatID=" + (row["categoryid"]).ToString();

                    // newNode.PopulateOnDemand = false;
                    //   newNode.SelectAction = TreeNodeSelectAction.None;
                    node.ChildItems.Add(newNode);
                    //node.NavigateUrl = "../UrunGoster.aspx?CatID=" + (row["categoryid"]).ToString();

                    FillTitlesForAuthors(newNode);
                }
            }
        }
        void click()
        {
            Response.Write(Menu1.SelectedItem.Text);
        }
        ////int olacak()
        ////{
        ////    Label1.Text = "";
        ////    string query = "Select * from categories where parentid=" + Menu1.SelectedValue + "";

        ////    DataTable dt = db.select(query);
        ////    if (dt.Rows.Count != 0)
        ////        Label1.Text = "Kategorilendirmede sonuna kadar gitmediniz";
        ////    else
        ////    {
        ////        // Label1.Text = " "+ Menu1.SelectedItem.Text+Label1.Text;
        ////        yolbul(Convert.ToInt32(Menu1.SelectedValue));
        ////    }
        ////    return 0;
        ////}
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Session["usertype"].ToString() == "")
            {
                Response.Redirect("HataSayfasi.aspx");
            }
            //int i = 1;
            //FileUpload myFileUpload = new FileUpload();

            //myFileUpload.ID = "upload_" + i.ToString();

            //this.Panel2.Controls.Add(myFileUpload);
            if (Label1.Text != "")
            {

                //Panel1.Controls.Clear();
                Label1.Text = "";
                string query = "Select * from categories where parentid=" + Menu1.SelectedValue + "";

                DataTable dt = db.select(query);
                if (dt.Rows.Count != 0)
                    Label1.Text = "Kategorilendirmede sonuna kadar gitmediniz";
                else
                {
                    // Label1.Text = " "+ Menu1.SelectedItem.Text+Label1.Text;
                    yolbul(Convert.ToInt32(Menu1.SelectedValue));
                }
            }

            if (!IsPostBack)
            {
                FillAuthors(Menu1.Items[0]);
               
            }
        }
        int yolbul(int childid)
        {


            tbl.Border = 2;
           
            string query1 = "Select * from categories where categoryid=" + childid + "";
            DataTable dt = db.select(query1);

            foreach (DataRow dr in dt.Rows)
            {
                Label1.Text = ">>>" + dr["categoryname"].ToString() + Label1.Text;
                string query2 = "SELECT attributevalues.attributeid,attributetypes.datatype, attributes.attributename FROM attributes INNER JOIN attributevalues ON attributes.attributeid = attributevalues.attributeid INNER JOIN attributetypes ON attributes.type = attributetypes.attributecode WHERE(attributes.categoryid = " + dr["categoryid"].ToString() + ") group by attributevalues.attributeid,attributetypes.datatype,attributes.attributename";
                DataTable dt2 = new DataTable();
                dt2 = db.select(query2);
                if (dt2.Rows.Count != 0)
                {
                    

                    foreach (DataRow dr2 in dt2.Rows)
                    {

                        HtmlTableRow r = new HtmlTableRow();
                        HtmlTableCell c = new HtmlTableCell();
                        r.Cells.Add(c);
                        c.Width = "450";
                        c = new HtmlTableCell();
                        r.Cells.Add(c);
                        tbl.Rows.Add(r);
                        Panel1.Controls.Add(tbl);
                        Label lr = new Label();

                        lr.Text = dr2["attributename"].ToString();
                        tbl.Rows[a].Cells[0].Controls.Add(lr);
                        
                       // Panel1.Controls.Add(lr);
                        string query3 = "SELECT  attributevalues.id, attributevalues.value FROM attributes INNER JOIN attributevalues ON attributes.attributeid = attributevalues.attributeid INNER JOIN attributetypes ON attributes.type = attributetypes.attributecode WHERE(attributes.categoryid = " + dr["categoryid"].ToString() + ") and attributevalues.attributeid='" + dr2["attributeid"].ToString() + "'";
                        DataTable dt3 = new DataTable();
                        dt3 = db.select(query3);

                        if (dr2["datatype"].ToString() == "combobox")
                        {
                            b[a] = "combobox";
                            DropDownList dwn2 = new DropDownList();
                           
                            dwn2.ID = a.ToString();
                            //Panel1.Controls.Add(dwn2);
                        
                             tbl.Rows[a].Cells[1].Controls.Add(dwn2);
                            ((DropDownList)Panel1.FindControl(a.ToString())).DataTextField = "value";
                            ((DropDownList)Panel1.FindControl(a.ToString())).DataValueField = "id";
                            ((DropDownList)Panel1.FindControl(a.ToString())).DataSource = dt3;
                            ((DropDownList)Panel1.FindControl(a.ToString())).DataBind();
                           

                            a++;
                         


                        }
                        if (dr2["datatype"].ToString() == "checkbox")
                        {
                            b[a] = "checkbox";
                            RadioButtonList ch = new RadioButtonList();


                            ch.ID = a.ToString();
                            tbl.Rows[a].Cells[1].Controls.Add(ch);

                            //Panel1.Controls.Add(ch);
                            // ch.Attributes = dt3;
                            ((RadioButtonList)Panel1.FindControl(a.ToString())).DataTextField = "value";
                            ((RadioButtonList)Panel1.FindControl(a.ToString())).DataValueField = "id";
                            ((RadioButtonList)Panel1.FindControl(a.ToString())).DataSource = dt3;
                            ((RadioButtonList)Panel1.FindControl(a.ToString())).DataBind();
                            a++;
                            Panel1.DataBind();
                            //Label2.Text = Label2.Text + " " + ((CheckBoxList)Panel1.FindControl((a-1).ToString())).SelectedItem.Text;


                        }




                    }
                }
                if (dr["parentid"].ToString() == "")
                    return 0;

                yolbul(Convert.ToInt32(dr["parentid"]));
            }

            return 0;

        }
        protected void click(object sender, MenuEventArgs e)
        {
            //Panel1.Controls.Remove(((DropDownList)Panel1.FindControl("1")));

            // Panel1.Controls.Clear();
            lb_Categoryid.Text = Menu1.SelectedValue.ToString();
            Menu1.Enabled = false;

            Label1.Text = "";
            string query = "Select * from categories where parentid=" + Menu1.SelectedValue + "";

            DataTable dt = db.select(query);
            if (dt.Rows.Count != 0)
                Label1.Text = "Kategorilendirmede sonuna kadar gitmediniz";
            else
            {
                // Label1.Text = " "+ Menu1.SelectedItem.Text+Label1.Text;
                yolbul(Convert.ToInt32(Menu1.SelectedValue));
            }



            //Response.Write(Menu1.SelectedItem.Text);


            Button1.Visible = true;
            myFileUpload.Focus();
        }

        protected void bt_Kaydet_Click(object sender, EventArgs e)
        {

            if ((Button1.Enabled != false) && (Label1.Text != "Kategorilendirmede sonuna kadar gitmediniz"))
            {
                Label1.Text = "";
                string c = "image\\" + lb_Resim.Text;
                db.insert("INSERT INTO productimage(productimage) VALUES (N'" + c + "')");
                string sr = "select productimageid from productimage where productimage=N'" + c + "'";
                DataTable dtimage = new DataTable();
                dtimage = db.select(sr);
                string simage = "";
                foreach (DataRow dr10 in dtimage.Rows)
                {
                    simage = dr10["productimageid"].ToString();
                }
                //Session["userid"] = "4";
                sr = "INSERT INTO products(userid, name, description, price, categoryid, productdate, deadline, available, imageid) VALUES (N'" + Session["userid"].ToString() + "',N'" + tb_UrunAdi.Text + "',N'" + tb_Bilgi.Text + "',N'" + tb_Fiyat.Text + "',N'" + lb_Categoryid.Text + "','" + DateTime.Now.ToString() + "',N'" + cal_SonTarih.SelectedDate.ToString("MM.dd.yyyy") + "',1,N'" + simage + "')";
                db.insert(sr);
                sr = "select top 1 productid from products order by productid desc";
                DataTable dtid = new DataTable();
                dtid = db.select(sr);
                foreach (DataRow dr11 in dtid.Rows)
                {
                    simage = dr11["productid"].ToString();
                }
                for (int i = 0; i < a; i++)
                {
                    //try
                    //{
                    if (b[i] == "combobox")
                    {
                        SqlDataSource2.InsertCommand = "INSERT INTO productattributes(productid, avid) VALUES ('" + simage + "','" + ((DropDownList)Panel1.FindControl(i.ToString())).SelectedValue.ToString() + "')";
                        SqlDataSource2.Insert();

                    }
                    if (b[i] == "checkbox")
                    {
                        SqlDataSource2.InsertCommand = "INSERT INTO productattributes(productid, avid) VALUES ('" + simage + "','" + ((RadioButtonList)Panel1.FindControl(i.ToString())).SelectedValue.ToString() + "')";

                        SqlDataSource2.Insert();
                    }
                    //}
                    //catch (Exception ex)
                    //{
                    //    Label2.Text = "Lutfen seciminizi yapiniz";
                    //}

                }
                Response.Redirect("Basardiniz.aspx");
            }
            else
            {
                Label9.Text = "Bir kategori Seciniz";
            }
        }

        protected void page_load(object sender, MenuEventArgs e)
        {

        }

        protected void cal(object sender, MenuEventArgs e)
        {

        }
        protected void bt_Tamam_Click(object sender, EventArgs e)
        {
            Button1.Visible = false;
            Response.Redirect("menemen2.aspx");
        }
        protected void bt_Tamam2_Click(object sender, EventArgs e)
        {
            if (cal_SonTarih.SelectedDate <= DateTime.Now)
                lb_TarihUyari.Text = "Bugunden daha buyuk bir tarih seciniz";
            else
                lb_TarihUyari.Text = cal_SonTarih.SelectedDate.ToString();
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            


         //   FileUpload myFileUpload = ((FileUpload)Panel1.FindControl("upload_" + i.ToString()));

            if (myFileUpload.HasFile)
            {
                if ((myFileUpload.PostedFile.ContentLength < 1000000) && (myFileUpload.PostedFile.ContentType == "image/pjpeg") || (myFileUpload.PostedFile.ContentType == "image/gif") ||
(myFileUpload.PostedFile.ContentType == "image/jpg") ||
(myFileUpload.PostedFile.ContentType == "image/jpeg") ||

                (myFileUpload.PostedFile.ContentType == "image/bmp"))
                {
                    lb_Resim.Text = ((-1) * DateTime.Now.ToBinary()) + myFileUpload.FileName;


                    myFileUpload.SaveAs(Server.MapPath("image/" + lb_Resim.Text));

                    lb_Resim2.Text = myFileUpload.FileName + " adli resminiz yuklendi";
                }
                else
                    lb_Resim2.Text = "Resiminiz boyutu cok buyuk";
            }
            else
            {
                lb_Resim2.Text = "*";
            }

           myFileUpload.Focus();
        }
        
    }
}
